<template>
	<view class="uni-container">
		<uni-forms ref="form" :value="formData" validate-trigger="submit" err-show-type="toast">
			<uni-forms-item name="state" label="状态">
				<switch @change="binddata('state', $event.detail.value)" :checked="formData.state"></switch>
			</uni-forms-item>
			<uni-forms-item name="cover" label="配图">
				<view class="cover-container">
					<uni-easyinput placeholder="每日英语配图"  v-model="formData.cover"></uni-easyinput>
					<button size="mini" class="upload-btn" @click="upload('cover')" type="primary">上传</button>
				</view>
			</uni-forms-item>
			<uni-forms-item name="audio" label="音频">
				<view class="cover-container">
					<uni-easyinput placeholder="每日英语音频"  v-model="formData.audio"></uni-easyinput>
					<button size="mini" class="upload-btn" @click="upload('audio')" type="primary">上传</button>
				</view>
			</uni-forms-item>
			<uni-forms-item name="content" label="内容">
				<uni-easyinput type="textarea" autoHeight placeholder="每日英语对应的内容" v-model="formData.content">
				</uni-easyinput>
			</uni-forms-item>
			<view class="uni-button-group">
				<button type="primary" class="uni-button" @click="submit">提交</button>
			</view>
		</uni-forms>
	</view>
</template>

<script>
	import {
		validator
	} from '../../js_sdk/validator/daily-english.js';

	const db = uniCloud.database();
	const dbCollectionName = 'daily-english';

	function getValidator(fields) {
		let result = {}
		for (let key in validator) {
			if (fields.indexOf(key) > -1) {
				result[key] = validator[key]
			}
		}
		return result
	}

	export default {
		data() {
			let formData = {
				"state": null,
				"text": "",
				"cover": "",
				"content": "",
				"audio":""
			}
			return {
				formData,
				formOptions: {},
				rules: {
					...getValidator(Object.keys(formData))
				}
			}
		},
		onReady() {
			this.$refs.form.setRules(this.rules)
		},
		methods: {
			/**
			 * 验证表单并提交
			 */
			submit() {
				uni.showLoading({
					mask: true
				})
				this.$refs.form.validate().then((res) => {
					return this.submitForm(res)
				}).catch(() => {}).finally(() => {
					uni.hideLoading()
				})
			},
			/**
			 * @param {Object} values 上传文件
			 */
			upload(key) {
				//前端代码
				uni.chooseImage({
					count: 1,
					success:async (res) => {
						if (res.tempFilePaths.length > 0) {
							let filePath = res.tempFilePaths[0]
							//进行上传操作
							// 文件命名的操作
							let myDate = new Date();
							let year = myDate.getFullYear(); //获取当前年份(2位)
							let month = myDate.getMonth() + 1; //获取当前月份(0-11,0代表1月)
							let day = myDate.getDate(); //获取当前日(1-31)
							let filename = `daily-english-${year}-${month}-${day}${key==='cover'?'.jpg':'mp3'}`
							// promise方式
							uni.showLoading({
								title: '上传中',
								mask: false
							});
							const result = await uniCloud.uploadFile({
								filePath: filePath,
								cloudPath: filename,
								onUploadProgress: function(progressEvent) {
									var percentCompleted = Math.round(
										(progressEvent.loaded * 100) / progressEvent.total
									);
									console.log(percentCompleted)
								}
							});
							if(result.success) uni.hideLoading()
							this.formData[key]=result.fileID
						}
					}
				});
			},

			/**
			 * 提交表单
			 */
			submitForm(value) {
				// 使用 clientDB 提交数据
				return db.collection(dbCollectionName).add(value).then((res) => {
					uni.showToast({
						icon: 'none',
						title: '新增成功'
					})
					this.getOpenerEventChannel().emit('refreshData')
					setTimeout(() => uni.navigateBack(), 500)
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				})
			}
		}
	}
</script>

<style>
	.uni-container {
		padding: 15px;
	}

	.uni-input-border,
	.uni-textarea-border {
		width: 100%;
		font-size: 14px;
		color: #666;
		border: 1px #e5e5e5 solid;
		border-radius: 5px;
		box-sizing: border-box;
	}

	.uni-input-border {
		padding: 0 10px;
		height: 35px;

	}

	.uni-textarea-border {
		padding: 10px;
		height: 80px;
	}

	.uni-button-group {
		margin-top: 50px;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		justify-content: center;
	}

	.uni-button {
		width: 184px;
		padding: 12px 20px;
		font-size: 14px;
		border-radius: 4px;
		line-height: 1;
		margin: 0;
	}
</style>
<style lang="scss" scoped>
	.cover-container {
		display: flex;
		flex-direction: row;

		.upload-btn {
			margin-left: 5px;
		}
	}
</style>
